package org.jeecg.modules.pick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.DateUtils;
import org.jeecg.constant.WarehouseConstant;
import org.jeecg.modules.in.entity.InOrderInfo;
import org.jeecg.modules.in.service.IInOrderInfoService;
import org.jeecg.modules.inventory.reportLabel.entity.ReportLabel;
import org.jeecg.modules.inventory.reportLabel.service.IReportLabelService;
import org.jeecg.modules.pick.entity.PickOrderDetail;
import org.jeecg.modules.pick.entity.PickOrderInfo;
import org.jeecg.modules.pick.mapper.PickOrderDetailMapper;
import org.jeecg.modules.pick.mapper.PickOrderInfoMapper;
import org.jeecg.modules.pick.service.IPickOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 理货管理
 * @Author: jeecg-boot
 * @Date: 2024-11-28
 * @Version: V1.0
 */
@Service
public class PickOrderInfoServiceImpl extends ServiceImpl<PickOrderInfoMapper, PickOrderInfo> implements IPickOrderInfoService {

    @Autowired
    private PickOrderInfoMapper pickOrderInfoMapper;
    @Autowired
    private PickOrderDetailMapper pickOrderDetailMapper;
    @Autowired
    private IInOrderInfoService inOrderInfoService;
    @Autowired
    private IReportLabelService reportLabelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePickOrder(PickOrderInfo pickOrderInfo, List<PickOrderDetail> pickOrderDetailList) {
        Assert.isTrue(StringUtils.isNotBlank(pickOrderInfo.getContainerNo()), "请输入集装箱号！");
        Assert.notNull(pickOrderInfo.getSkuType(), "请选择品番类型！");
        // 过滤全部为空的数据
        pickOrderDetailList = pickOrderDetailList.stream().filter(data -> !(StringUtils.isBlank(data.getStackCode()) && StringUtils.isBlank(data.getSkuCode()) && null == data.getBoxQuantity())).collect(Collectors.toList());
        // 校验必填字段
        long count = pickOrderDetailList.stream().filter(data -> StringUtils.isBlank(data.getStackCode()) || StringUtils.isBlank(data.getSkuCode()) || null == data.getBoxQuantity()).count();
        Assert.isTrue(count == 0, "货垛码、品番编码、箱子数量、物品数量必须填写！");

        if (StringUtils.isBlank(pickOrderInfo.getPickOrderCode())) {
            pickOrderInfo.setPickOrderCode(DateUtils.getToday() + "_" + UUID.randomUUID().toString().replace("-", ""));
        } else {
            int orderCodeCount = inOrderInfoService.count(new LambdaQueryWrapper<InOrderInfo>()
                    .eq(InOrderInfo::getInOrderCode, pickOrderInfo.getPickOrderCode())
                    .ne(InOrderInfo::getStatus, WarehouseConstant.EnterWarehouseStatusEnum.DELETE.getCode()));
            Assert.isTrue(orderCodeCount == 0, "订单号【%s】已存在！", pickOrderInfo.getPickOrderCode());
        }
        // todo：正常应该做递归确保不重复，暂时先做成用户自己再提交一次 保证订单号不重复
        int orderCodeCount = reportLabelService.count(new LambdaQueryWrapper<ReportLabel>().eq(ReportLabel::getInOrderCode, pickOrderInfo.getPickOrderCode()));
        Assert.isTrue(orderCodeCount == 0, "出现位未知异常，请重新提交，如问题依旧可联系管理员！");

        if (null == pickOrderInfo.getPickOrderTime()) {
            pickOrderInfo.setPickOrderTime(new Date());
        }

        if (StringUtils.isBlank(pickOrderInfo.getId())) {
            this.saveMain(pickOrderInfo, pickOrderDetailList);
        } else {
            this.updateMain(pickOrderInfo, pickOrderDetailList);
        }
    }

    @Override
    @Transactional
    public void saveMain(PickOrderInfo pickOrderInfo, List<PickOrderDetail> pickOrderDetailList) {
        pickOrderInfoMapper.insert(pickOrderInfo);
        if (CollectionUtils.isNotEmpty(pickOrderDetailList)) {
            for (PickOrderDetail entity : pickOrderDetailList) {
                //外键设置
                entity.setPickOrderId(pickOrderInfo.getId());
                pickOrderDetailMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateMain(PickOrderInfo pickOrderInfo, List<PickOrderDetail> pickOrderDetailList) {
        pickOrderInfoMapper.updateById(pickOrderInfo);

        //1.先删除子表数据
        pickOrderDetailMapper.deleteByMainId(pickOrderInfo.getId());

        //2.子表数据重新插入
        if (CollectionUtils.isNotEmpty(pickOrderDetailList)) {
            for (PickOrderDetail entity : pickOrderDetailList) {
                //外键设置
                entity.setPickOrderId(pickOrderInfo.getId());
                pickOrderDetailMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
        PickOrderInfo pickOrder = pickOrderInfoMapper.selectById(id);
        Assert.notNull(pickOrder, "理货单数据异常，无法删除！");
        Assert.isTrue(Arrays.asList(WarehouseConstant.PickWarehouseStatusEnum.CREATE_END.getCode(), WarehouseConstant.PickWarehouseStatusEnum.RELEASE_END.getCode()).contains(pickOrder.getStatus()),
                "只有未发布或已发布的理货单才可删除，理货后的理货单不支持删除！");
        pickOrder.setStatus(WarehouseConstant.PickWarehouseStatusEnum.DELETE.getCode());
        pickOrderInfoMapper.updateById(pickOrder);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            this.delMain(id.toString());
        }
    }

}
